// BigeMapUtils：Bigemap地图工具类，封装了点、线、面、圆、测距、测面积、围栏等绘制与交互逻辑
class BigeMapUtils {
    constructor(mapContainerId, mapType, options = {}) {
        this.map = null; // 地图实例
        this.polygonCoords = []; // 当前点/线/面/围栏的坐标数组
        this.graphicsLayer = null; // 当前点/线/面图层（用于统一管理）
        this.mapContainerId = mapContainerId; // 地图容器ID
        this.mapType = mapType; // 地图类型
        this.options = options; // 初始化参数
        this.onClickCallback = options.onClickCallback || null; // 坐标变化回调
        this.drawMode = 'polygon'; // 当前绘制模式，默认多边形，可切换 'point' | 'line' | 'polygon' | 'circle' | 'distance' | 'area' | 'fence' | 'clear'
        this.strokeColor = '#333'; // 边框颜色
        this.fillColor = '#333'; // 填充颜色
        this.lineType = 'solid'; // 线型，支持'solid'|'dashed'
        this._fenceHistory = []; // 围栏历史图层（可保留多个围栏）
        // 拖动画线相关
        this._isDrawingLine = false; // 是否正在拖拽画线
        this._lastLinePoint = null; // 画线时上一个点
        this._lineDragThreshold = 5; // 拖动画线时采点距离阈值（米）
        // 新增：初始化点和多边形历史数组
        this._polylineHistory = [];
        this._polygonHistory = [];
        // 新增：初始化点历史数组
        this._pointHistory = [];
    }

    // 初始化地图，加载Bigemap并设置中心、缩放、边界等
    initMap() {
        if (typeof BM === 'undefined') {
            throw new Error('Bigemap API 未加载'); // Bigemap未加载时报错
        }
        BM.Config.HTTP_URL = this.options.httpUrl || 'http://192.168.110.210:3000'; // 地图服务地址
        BM.accessToken = this.options.accessToken || ''; // 访问令牌
        const finalMapType = this.mapType || this.options.mapType || 'bigemap.2i5fd1il'; // 地图类型
        this.map = BM.map(this.mapContainerId, finalMapType, {
            center: this.options.center, // 地图中心点
            zoom: this.options.zoom || 6, // 默认缩放级别
            zoomControl: true // 显示缩放控件
        });
        if (this.options.fitBounds) {
            this.map.fitBounds(this.options.fitBounds); // 设置显示边界
        }
        this.bindEvents(); // 绑定所有交互事件
    }

    /**
     * 绑定地图所有交互事件，根据drawMode实现不同的绘制/测量/围栏逻辑
     * 支持点、线、多边形、圆、测距、测面积、围栏、清除
     */
    bindEvents() {
        // 地图左键点击事件
        this.map.on('click', (e) => {
            console.log('地图点击', this.drawMode, e.latlng);
            // 只响应地图容器本身的点击，防止干扰
            if (e.originalEvent.target.id !== this.mapContainerId) return;
            const latlng = e.latlng;
            // 画点模式
            if (this.drawMode === 'point') {
                const point = { lat: latlng.lat, lng: latlng.lng, id: Date.now() + Math.random() };
                this._pointHistory.push(point);
                this.drawGraphics(); // 重新渲染所有点
                if (this.onClickCallback) {
                    this.onClickCallback(this.getCoords()); // 通知外部坐标变化
                }
            // 画线
            } else if (this.drawMode === 'line') {
                console.log('进入画线分支');
                this.polygonCoords.push({ lat: latlng.lat, lng: latlng.lng });
                this.drawGraphics();
            // 画多边形
            } else if (this.drawMode === 'polygon') {
                console.log('进入画面分支');
                this.polygonCoords.push({ lat: latlng.lat, lng: latlng.lng });
                this.drawGraphics();
            // 拖拽画圆
            } // 画圆逻辑移到mousedown/mousemove/mouseup
            // 测距/测面积：点击添加点，双击结束
            else if (this.drawMode === 'distance' || this.drawMode === 'area') {
                console.log('进入测距/测面积分支');
                if (!this._measureCoords) this._measureCoords = [];
                this._measureCoords.push({ lat: latlng.lat, lng: latlng.lng });
                if (this._measureLayer) this.map.removeLayer(this._measureLayer);
                // 清除旧的序号marker
                if (this._measureMarkers) {
                  this._measureMarkers.forEach(m => this.map.removeLayer(m));
                }
                this._measureMarkers = this._measureCoords.map((pt, idx) => {
                  return BM.marker([pt.lat, pt.lng], {
                    icon: BM.divIcon({
                      className: 'distance-index-icon',
                      html: `<div style="background:#2d8cf0;color:#fff;border-radius:50%;width:22px;height:22px;display:flex;align-items:center;justify-content:center;font-size:14px;border:2px solid #fff;">${idx+1}</div>`,
                      iconSize: [22, 22],
                      iconAnchor: [11, 11]
                    })
                  }).addTo(this.map);
                });
                if (this._measureCoords.length > 1) {
                    const latlngs = this._measureCoords.map(m => [m.lat, m.lng]);
                    if (this.drawMode === 'distance') {
                        // 测距为虚线
                        this._measureLayer = BM.polyline(latlngs, { color: this.strokeColor, dashArray: '5,5' }).addTo(this.map);
                    } else {
                        // 测面积为多边形
                        this._measureLayer = BM.polygon(latlngs, { color: this.strokeColor, fillColor: this.fillColor, fillOpacity: 0.2 }).addTo(this.map);
                    }
                } else {
                    this._measureLayer = BM.marker([latlng.lat, latlng.lng]).addTo(this.map);
                }
            // 画围栏：点击添加点，双击结束
            } else if (this.drawMode === 'fence') {
                console.log('进入围栏分支');
                if (!this._fenceCoords) this._fenceCoords = [];
                this._fenceCoords.push({ lat: latlng.lat, lng: latlng.lng });
                if (this._fenceLayer) this.map.removeLayer(this._fenceLayer);
                if (this._fenceCoords.length > 2) {
                    const latlngs = this._fenceCoords.map(m => [m.lat, m.lng]);
                    this._fenceLayer = BM.polygon(latlngs, { color: this.strokeColor, fillColor: this.fillColor, fillOpacity: 0.2, dashArray: '5,5' }).addTo(this.map);
                } else if (this._fenceCoords.length > 1) {
                    const latlngs = this._fenceCoords.map(m => [m.lat, m.lng]);
                    this._fenceLayer = BM.polyline(latlngs, { color: this.strokeColor, dashArray: '5,5' }).addTo(this.map);
                } else {
                    this._fenceLayer = BM.marker([latlng.lat, latlng.lng]).addTo(this.map);
                }
            }
        });

        // 拖拽绘制圆形
        let isDrawingCircle = false; // 是否正在拖拽画圆
        let circleCenter = null;     // 圆心坐标
        let tempCircle = null;       // 临时圆对象
        let mouseDownLatLng = null;  // 鼠标按下时的坐标
        // let lastDrawnCircle = null;  // 最后一个已保存的圆（废弃，改为数组）
        this._circleList = [];       // 存储所有已画的圆
        let currentCircleRadius = 0; // 记录当前临时圆半径

        // 鼠标左键按下，准备画圆
        this.map.on('mousedown', (e) => {
            // 只允许左键（button===0）且在画圆模式下
            if (this.drawMode === 'circle' && e.originalEvent.button === 0 && e.originalEvent.target.id === this.mapContainerId) {
                isDrawingCircle = true;
                circleCenter = e.latlng;
                mouseDownLatLng = e.latlng;
                if (tempCircle) {
                    this.map.removeLayer(tempCircle);
                    tempCircle = null;
                }
                // 禁止地图拖动
                this.map.dragging && this.map.dragging.disable();
            }
        });
        // 鼠标移动，动态调整临时圆
        this.map.on('mousemove', (e) => {
            if (this.drawMode === 'circle' && isDrawingCircle && circleCenter) {
                const radius = this.map.distance(circleCenter, e.latlng);
                currentCircleRadius = radius; // 记录当前半径
                if (tempCircle) {
                    this.map.removeLayer(tempCircle);
                }
                // 画一个临时圆
                tempCircle = BM.circle([circleCenter.lat, circleCenter.lng], {
                    radius,
                    color: this.strokeColor,
                    fillColor: this.fillColor,
                    fillOpacity: 0.2
                }).addTo(this.map);
            }
        });
        // 鼠标左键松开，结束临时圆拖拽
        this.map.on('mouseup', (e) => {
            if (this.drawMode === 'circle' && isDrawingCircle && circleCenter && e.originalEvent.button === 0) {
                isDrawingCircle = false;
                // 不直接保存，只是结束拖拽，等双击时保存
                // 恢复地图拖动
                this.map.dragging && this.map.dragging.enable();
            }
        });
        // 双击时，保存当前圆形为正式图层
        this.map.on('dblclick', (e) => {
            if (this.drawMode === 'circle' && tempCircle && circleCenter) {
                // 阻止地图默认双击加点行为
                if (e.originalEvent) {
                    e.originalEvent.preventDefault();
                    e.originalEvent.stopPropagation();
                }
                // 用当前临时圆半径保存
                const radius = currentCircleRadius;
                const circle = BM.circle([circleCenter.lat, circleCenter.lng], {
                    radius,
                    color: this.strokeColor,
                    fillColor: this.fillColor,
                    fillOpacity: 0.2
                }).addTo(this.map);
                circle.on('contextmenu', (evt) => {
                    this.map.removeLayer(circle);
                    const idx = this._circleList.indexOf(circle);
                    if (idx !== -1) this._circleList.splice(idx, 1);
                    if (evt.originalEvent && evt.originalEvent.preventDefault) evt.originalEvent.preventDefault();
                    return false;
                });
                this._circleList.push(circle);
                this.map.removeLayer(tempCircle);
                tempCircle = null;
                circleCenter = null;
                // 可选：回调通知外部
                if (this.onClickCallback) {
                    this.onClickCallback(this._circleList.map(c => {
                        const latlng = c.getLatLng();
                        return { lat: latlng.lat, lng: latlng.lng, radius: c.getRadius() };
                    }));
                }
            }
        });
        // 拖动画线：按下左键开始，移动时自动加点，松开左键结束
        this.map.on('mousedown', (e) => {
            if (this.drawMode === 'line' && e.originalEvent.button === 0 && e.originalEvent.target.id === this.mapContainerId) {
                this._isDrawingLine = true;
                this._lastLinePoint = e.latlng;
                if (!Array.isArray(this.polygonCoords)) this.polygonCoords = [];
                this.polygonCoords.push({ lat: e.latlng.lat, lng: e.latlng.lng });
                this.drawGraphics();
                // 禁用地图拖动
                this.map.dragging && this.map.dragging.disable();
            }
        });
        this.map.on('mousemove', (e) => {
            if (this.drawMode === 'line' && this._isDrawingLine) {
                // 计算与上一个点的距离，超过一定阈值才加点
                const last = this._lastLinePoint;
                const curr = e.latlng;
                if (last) {
                   const dist = this.map.distance([last.lat, last.lng], [curr.lat, curr.lng]);
                   if (dist > this._lineDragThreshold) {
                       this.polygonCoords.push({ lat: curr.lat, lng: curr.lng });
                       this._lastLinePoint = curr;
                       this.drawGraphics();
                   }
                }
            }
        });
        this.map.on('mouseup', (e) => {
            if (this.drawMode === 'line' && this._isDrawingLine && e.originalEvent.button === 0) {
                this._isDrawingLine = false;
                this._lastLinePoint = null;
                // 恢复地图拖动
                this.map.dragging && this.map.dragging.enable();
                // 结束后可选：自动回调一次
                if (this.polygonCoords.length > 1 && this.onClickCallback) {
                    this.onClickCallback(this.getCoords());
                }
            }
        });
        // 右键点击 marker 删除点（只在 marker 身上才删除）
        this.map.on('contextmenu', (e) => {
            if (this.drawMode === 'point' && this.polygonCoords.length > 0) {
                // 计算距离最近的点
                let minDist = Infinity;
                let minIdx = -1;
                const mousePoint = this.map.latLngToContainerPoint(e.latlng);
                this.polygonCoords.forEach((pt, idx) => {
                    const markerPoint = this.map.latLngToContainerPoint([pt.lat, pt.lng]);
                    const dist = markerPoint.distanceTo(mousePoint);
                    if (dist < minDist) {
                        minDist = dist;
                        minIdx = idx;
                    }
                });
                // 20像素内认为点中了marker
                // if (minIdx !== -1 && minDist < 20) {
                //     this.polygonCoords.splice(minIdx, 1);
                //     this.drawGraphics();
                //     if (this.onClickCallback) this.onClickCallback(this.getCoords());
                //     if (e.originalEvent && e.originalEvent.preventDefault) e.originalEvent.preventDefault();
                //     return false;
                // }
            }
            // 右键点击，撤销最后一个点/测量点/围栏点
            if (this.drawMode === 'distance' || this.drawMode === 'area') {
                if (this._measureCoords && this._measureCoords.length > 0) {
                    this._measureCoords.pop();
                    if (this._measureLayer) { this.map.removeLayer(this._measureLayer); this._measureLayer = null; }
                    if (this._measureCoords.length > 1) {
                        const latlngs = this._measureCoords.map(m => [m.lat, m.lng]);
                        if (this.drawMode === 'distance') {
                            this._measureLayer = BM.polyline(latlngs, { color: this.strokeColor, dashArray: '5,5' }).addTo(this.map);
                        } else {
                            this._measureLayer = BM.polygon(latlngs, { color: this.strokeColor, fillColor: this.fillColor, fillOpacity: 0.2 }).addTo(this.map);
                        }
                    } else if (this._measureCoords.length === 1) {
                        this._measureLayer = BM.marker([this._measureCoords[0].lat, this._measureCoords[0].lng]).addTo(this.map);
                    }
                }
            } else if (this.polygonCoords.length > 0) {
                this.polygonCoords.pop();
                this.drawGraphics();
                if (this.onClickCallback) {
                    this.onClickCallback(this.getCoords());
                }
            } else if (this.drawMode === 'fence') {
                if (this._fenceCoords && this._fenceCoords.length > 0) {
                    this._fenceCoords.pop();
                    if (this._fenceLayer) { this.map.removeLayer(this._fenceLayer); this._fenceLayer = null; }
                    if (this._fenceCoords.length > 2) {
                        const latlngs = this._fenceCoords.map(m => [m.lat, m.lng]);
                        this._fenceLayer = BM.polygon(latlngs, { color: this.strokeColor, fillColor: this.fillColor, fillOpacity: 0.2, dashArray: '5,5' }).addTo(this.map);
                    } else if (this._fenceCoords.length > 1) {
                        const latlngs = this._fenceCoords.map(m => [m.lat, m.lng]);
                        this._fenceLayer = BM.polyline(latlngs, { color: this.strokeColor, dashArray: '5,5' }).addTo(this.map);
                    } else if (this._fenceCoords.length === 1) {
                        this._fenceLayer = BM.marker([this._fenceCoords[0].lat, this._fenceCoords[0].lng]).addTo(this.map);
                    }
                }
            }
        });
        // 双击结束线/面/测距/测面积/围栏并回调
        this.map.on('dblclick', (e) => {
            if (e.originalEvent && e.originalEvent.button !== 0) return;
            // 结束画线
            if (this.drawMode === 'line' && this.polygonCoords.length > 1) {
                // 新增：保留历史线
                const latlngs = this.polygonCoords.map(m => [m.lat, m.lng]);
                const polyline = BM.polyline(latlngs, { color: this.strokeColor,weight:8 }).addTo(this.map);
                // 右键删除
                polyline.on('contextmenu', (evt) => {
                    this.map.removeLayer(polyline);
                    const idx = this._polylineHistory.indexOf(polyline);
                    if (idx !== -1) this._polylineHistory.splice(idx, 1);
                    if (evt.originalEvent && evt.originalEvent.preventDefault) evt.originalEvent.preventDefault();
                    return false;
                });
                this._polylineHistory.push(polyline);

                if (this.onClickCallback) {
                    this.onClickCallback(this.getCoords());
                }
                // 清空当前线坐标
                this.polygonCoords = [];
                this.drawGraphics();
            // 结束画多边形
            } else if (this.drawMode === 'polygon' && this.polygonCoords.length > 2) {
                // 新增：保留历史多边形
                const latlngs = this.polygonCoords.map(m => [m.lat, m.lng]);
                const polygon = BM.polygon(latlngs, { color: this.strokeColor, fillColor: this.fillColor, fillOpacity: 0.2 }).addTo(this.map);
                // 右键删除
                polygon.on('contextmenu', (evt) => {
                    this.map.removeLayer(polygon);
                    const idx = this._polygonHistory.indexOf(polygon);
                    if (idx !== -1) this._polygonHistory.splice(idx, 1);
                    if (evt.originalEvent && evt.originalEvent.preventDefault) evt.originalEvent.preventDefault();
                    return false;
                });
                this._polygonHistory.push(polygon);

                if (this.onClickCallback) {
                    this.onClickCallback(this.getCoords());
                }
                // 清空当前多边形坐标
                this.polygonCoords = [];
                this.drawGraphics();
            // 结束测距，计算总距离和角度，显示tooltip，线条保留
            } else if (this.drawMode === 'distance' && this._measureCoords && this._measureCoords.length > 1) {
                let total = 0;
                for (let i = 1; i < this._measureCoords.length; i++) {
                    total += this.map.distance(
                        [this._measureCoords[i-1].lat, this._measureCoords[i-1].lng],
                        [this._measureCoords[i].lat, this._measureCoords[i].lng]
                    );
                }
                // 计算角度（首尾两点）
                const start = this._measureCoords[0];
                const end = this._measureCoords[this._measureCoords.length - 1];
                const angle = this._calcAzimuth(start.lat, start.lng, end.lat, end.lng);
                // 保留所有测距线和tooltip
                if (!this._distanceHistory) this._distanceHistory = [];
                const latlngs = this._measureCoords.map(m => [m.lat, m.lng]);
                const lineLayer = BM.polyline(latlngs, { color: this.strokeColor, dashArray: '5,5' }).addTo(this.map);
                // 绑定右键删除事件
                lineLayer.on('contextmenu', (e) => {
                    this.map.removeLayer(lineLayer);
                    if (tipMarker) this.map.removeLayer(tipMarker);
                    const idx = this._distanceHistory.findIndex(item => item.line === lineLayer);
                    if (idx !== -1) this._distanceHistory.splice(idx, 1);
                    if (e.originalEvent && e.originalEvent.preventDefault) e.originalEvent.preventDefault();
                    this.drawGraphics();
                    return false;
                });
                // 在最后一个点显示距离tooltip
                const tipMarker = BM.marker([end.lat, end.lng], { opacity: 0, interactive: false })
                  .addTo(this.map)
                  .bindTooltip(
                    `距离 ${(total/1000).toFixed(2)} km<br>角度 ${angle.toFixed(2)}°`,
                    { permanent: true, direction: 'right', className: 'distance-tooltip' }
                  )
                  .openTooltip();
                // 清除所有测量点的序号 marker
                if (this._measureMarkers) {
                    this._measureMarkers.forEach(m => this.map.removeLayer(m));
                    this._measureMarkers = null;
                }
                this._distanceHistory.push({ line: lineLayer, tip: tipMarker });
                if (this.onClickCallback) {
                    this.onClickCallback({ coords: this._measureCoords, distance: total, angle });
                }
                this._measureCoords = [];
                if (this._measureLayer) { this.map.removeLayer(this._measureLayer); this._measureLayer = null; }
            // 结束测面积，计算多边形面积
            } else if (this.drawMode === 'area' && this._measureCoords && this._measureCoords.length > 2) {
                // 自动闭合多边形
                let coords = [...this._measureCoords];
                if (
                  coords.length > 2 &&
                  (coords[0].lat !== coords[coords.length - 1].lat ||
                    coords[0].lng !== coords[coords.length - 1].lng)
                ) {
                  coords.push({ ...coords[0] });
                }
                const area = this._calcPolygonArea(coords);
                // 先移除旧的测量图层（不再移除历史多边形）
                if (this._measureLayer) {
                  this.map.removeLayer(this._measureLayer);
                  this._measureLayer = null;
                }
                // 用闭合后的 coords 绘制多边形
                const polygonLayer = BM.polygon(
                  coords.map(m => [m.lat, m.lng]),
                  { color: this.strokeColor, fillColor: this.fillColor, fillOpacity: 0.2 }
                ).addTo(this.map);
                // 绑定右键删除事件
                polygonLayer.on('contextmenu', (e) => {
                    this.map.removeLayer(polygonLayer);
                    if (tipMarker) this.map.removeLayer(tipMarker);
                    const idx = this._areaHistory.findIndex(item => item.polygon === polygonLayer);
                    if (idx !== -1) {
                        this._areaHistory.splice(idx, 1);
                        // 删除对应的角点 marker
                        if (this._areaMarkers && this._areaMarkers[idx]) {
                            this._areaMarkers[idx].forEach(m => {
                                if (m && this.map.hasLayer(m)) this.map.removeLayer(m);
                            });
                            this._areaMarkers.splice(idx, 1);
                        }
                    }
                    if (e.originalEvent && e.originalEvent.preventDefault) e.originalEvent.preventDefault();
                    this.drawGraphics();
                    return false;
                });
                // 在最后一个点显示面积tooltip
                const end = coords[coords.length - 1];
                const tipMarker = BM.marker([end.lat, end.lng], { opacity: 0, interactive: false })
                  .addTo(this.map)
                  .bindTooltip(
                    `面积 ${(area/1000000).toFixed(2)} km²`,
                    { permanent: true, direction: 'right', className: 'distance-tooltip' }
                  )
                  .openTooltip();
                // 清除所有测量点的序号 marker
                if (this._measureMarkers) {
                    this._measureMarkers.forEach(m => this.map.removeLayer(m));
                    this._measureMarkers = null;
                }
                if (!this._areaHistory) this._areaHistory = [];
                this._areaHistory.push({ polygon: polygonLayer, tip: tipMarker });
                // 先移除旧的点marker（不再移除，改为累积）
                if (!this._areaMarkers) this._areaMarkers = [];
                const markers = coords.map(pt =>
                  BM.circleMarker([pt.lat, pt.lng], {
                    radius: 6,
                    color: this.strokeColor,
                    fillColor: this.fillColor,
                    fillOpacity: 1
                  }).addTo(this.map)
                );
                console.log('测面积结束，push markers 前', this._areaMarkers);
                this._areaMarkers.push(markers);
                console.log('测面积结束，push markers 后', this._areaMarkers);
                if (this.onClickCallback) {
                    this.onClickCallback({ coords, area });
                }
                this._measureCoords = [];
            // 结束围栏绘制并回调
            } else if (this.drawMode === 'fence' && this._fenceCoords && this._fenceCoords.length > 2) {
                if (this.onClickCallback) {
                    this.onClickCallback(this._fenceCoords);
                }
                // 保留围栏图层到历史，不移除
                if (this._fenceLayer) {
                    this._fenceHistory = this._fenceHistory || [];
                    this._fenceHistory.push(this._fenceLayer);
                    // 不移除图层
                    this._fenceLayer = null;
                }
                this._fenceCoords = [];
            }
        });
    }

    /**
     * 切换绘制模式
     * @param {string} mode - 'point' | 'line' | 'polygon' | 'circle' | 'distance' | 'area' | 'fence' | 'clear'
     * 会自动清空当前图形和坐标，并初始化相关状态
     */
    setDrawMode(mode) {
        this.drawMode = mode;
        this.polygonCoords = [];
        this.drawGraphics();
        // 新增：清除、圆、测距、测面积、围栏初始化
        if (mode === 'clear') {
            // 清除测面积的点位（必须放在最前面，确保不会被 return 跳过）
            if (this._areaMarkers) {
                this._areaMarkers.flat().forEach(m => {
                    if (m && this.map.hasLayer(m)) this.map.removeLayer(m);
                });
                this._areaMarkers = [];
            }
            this.polygonCoords = [];
            this.drawGraphics();
            // 清除所有点历史
            if (this._pointMarkers) {
                this._pointMarkers.forEach(m => { if (m && this.map.hasLayer(m)) this.map.removeLayer(m); });
                this._pointMarkers = [];
            }
            if (this._pointHistory) {
                this._pointHistory = [];
            }
            // 终极兜底：强制移除所有 marker/circleMarker 及 distance-index-icon
            this.map.eachLayer(layer => {
                // Leaflet原生
                if (typeof L !== 'undefined' && (layer instanceof L.Marker || layer instanceof L.CircleMarker)) {
                    this.map.removeLayer(layer);
                }
                // Bigemap自定义
                if (typeof BM !== 'undefined' && (layer instanceof BM.Marker || layer instanceof BM.CircleMarker)) {
                    this.map.removeLayer(layer);
                }
                // 兜底：移除带有 distance-index-icon 的 marker
                if (layer.options && layer.options.icon && layer.options.icon.options && layer.options.icon.options.className && layer.options.icon.options.className.includes('distance-index-icon')) {
                    this.map.removeLayer(layer);
                }
            });
            // 清除所有测距历史
            if (this._distanceHistory) {
                this._distanceHistory.forEach(item => {
                    if (item.line) this.map.removeLayer(item.line);
                    if (item.tip) this.map.removeLayer(item.tip);
                });
                this._distanceHistory = [];
            }
            // 清除所有面积历史
            if (this._areaHistory) {
                this._areaHistory.forEach(item => {
                    if (item.polygon) this.map.removeLayer(item.polygon);
                    if (item.tip) this.map.removeLayer(item.tip);
                });
                this._areaHistory = [];
            }
            if (this._distanceTipMarker) {
                this.map.removeLayer(this._distanceTipMarker);
                this._distanceTipMarker = null;
            }
            if (this.onClickCallback) this.onClickCallback([]);
            if (mode === 'circle') {
                this._circleCenter = null; // 画圆时，第一次点击为圆心
            }
            if (mode === 'distance' || mode === 'area') {
                this._measureCoords = []; // 测距/测面积时的点集
                this._measureLayer = null; // 临时图层
            }
            if (mode === 'fence') {
                this._fenceCoords = [];
                this._fenceLayer = null;
            }
            // 清除所有围栏历史
            if (this._fenceHistory) {
                this._fenceHistory.forEach(layer => {
                    if (layer && this.map.hasLayer(layer)) this.map.removeLayer(layer);
                });
                this._fenceHistory = [];
            }
            // 清除所有线历史
            if (this._polylineHistory) {
                this._polylineHistory.forEach(line => {
                    if (line && this.map.hasLayer(line)) this.map.removeLayer(line);
                });
                this._polylineHistory = [];
            }
            // 清除所有多边形历史
            if (this._polygonHistory) {
                this._polygonHistory.forEach(polygon => {
                    if (polygon && this.map.hasLayer(polygon)) this.map.removeLayer(polygon);
                });
                this._polygonHistory = [];
            }
        }
    }

    /**
     * 设置当前绘制颜色
     * @param {Object} param0
     * @param {string} param0.strokeColor - 边框色
     * @param {string} param0.fillColor - 填充色
     */
    setDrawColor({ strokeColor, fillColor, lineType }) {
        if (strokeColor) this.strokeColor = strokeColor;
        if (fillColor) this.fillColor = fillColor;
        if (lineType) this.lineType = lineType;
    }

    clearGraphics() {
        if (this.graphicsLayer) {
            this.map.removeLayer(this.graphicsLayer);
            this.graphicsLayer = null;
        }
        // 新增：清除回显层
        if (this._showPolygonLayer) {
            this.map.removeLayer(this._showPolygonLayer);
            this._showPolygonLayer = null;
        }
    }

    drawGraphics() {
        this.clearGraphics(); // 先清除上一次的图层
        const count = this.polygonCoords.length;
        const dashArray = this.lineType === 'dashed' ? '5,5' : null;
        // 只画了一个点时
        if (count === 1) {
            const { lat, lng } = this.polygonCoords[0];
            if (this.drawMode === 'point') {
                // 创建一个marker（点）
                const marker = BM.marker([lat, lng], {
                    // icon: BM.icon({ ... }) // 可自定义图标
                });
                // 绑定永久tooltip显示经纬度
                marker.bindTooltip(`经度: ${lng.toFixed(6)}<br>纬度: ${lat.toFixed(6)}`, {
                    permanent: true,
                    direction: 'right',
                    className: 'point-coord-tooltip'
                }).openTooltip();
                // 右键点击marker时，删除该点
                marker.on('contextmenu', (e) => {
                    // 获取当前marker的经纬度
                    const { lat, lng } = e.target.getLatLng();
                    // 在polygonCoords中查找对应点的索引
                    const index = this.polygonCoords.findIndex(item =>
                        Math.abs(item.lat - lat) < 1e-8 && Math.abs(item.lng - lng) < 1e-8
                    );
                    if (index !== -1) {
                        console.log('右键删除点：', { lat, lng, index });
                        this.polygonCoords.splice(index, 1); // 删除该点
                        this.drawGraphics(); // 重新渲染
                        if (this.onClickCallback) this.onClickCallback(this.getCoords());
                    }
                    // 阻止浏览器默认右键菜单
                    if (e.originalEvent && e.originalEvent.preventDefault) e.originalEvent.preventDefault();
                    return false;
                });
                // 用layerGroup包裹marker并添加到地图，便于后续统一管理
                this.graphicsLayer = BM.layerGroup([marker]).addTo(this.map);
            } else {
                // 其他模式下只画圆点
                this.graphicsLayer = BM.circleMarker([lat, lng], {
                    radius: 6, // 可根据需要调整
                    color: this.strokeColor,
                    fillColor: this.fillColor,
                    fillOpacity: 1
                }).addTo(this.map);
            }
        // 多于一个点时
        } else if (this.drawMode === 'point') {
            // 为每个点创建marker
            const markers = this.polygonCoords.map((pt) => {
                const marker = BM.marker([pt.lat, pt.lng], {
                    // icon: BM.icon({ ... })
                }).addTo(this.map);
                // 绑定永久tooltip显示经纬度
                marker.bindTooltip(`经度: ${pt.lng.toFixed(6)}<br>纬度: ${pt.lat.toFixed(6)}`, {
                    permanent: true,
                    direction: 'right',
                    className: 'point-coord-tooltip'
                }).openTooltip();
                // 右键点击marker时，删除该点
                marker.on('contextmenu', (e) => {
                    const { lat, lng } = e.target.getLatLng();
                    const index = this.polygonCoords.findIndex(item =>
                        Math.abs(item.lat - lat) < 1e-8 && Math.abs(item.lng - lng) < 1e-8
                    );
                    if (index !== -1) {
                        console.log('右键删除点：', { lat, lng, index });
                        this.polygonCoords.splice(index, 1);
                        this.drawGraphics();
                        if (this.onClickCallback) this.onClickCallback(this.getCoords());
                    }
                    if (e.originalEvent && e.originalEvent.preventDefault) e.originalEvent.preventDefault();
                    return false;
                });
                return marker;
            });
            // 用layerGroup包裹所有marker并添加到地图
            this.graphicsLayer = BM.layerGroup(markers).addTo(this.map);
        // 画线模式：只显示线，不显示点
        } else if (this.drawMode === 'line' && count >= 2) {
            const latlngs = this.polygonCoords.map(m => [m.lat, m.lng]);
            const polyline = BM.polyline(latlngs, { color: this.strokeColor, dashArray });
            this.graphicsLayer = polyline.addTo(this.map);
        // 画面模式，2个点时显示线和点，3个及以上显示多边形和所有点
        } else if (this.drawMode === 'polygon' && count === 2) {
            const latlngs = this.polygonCoords.map(m => [m.lat, m.lng]);
            const polyline = BM.polyline(latlngs, { color: this.strokeColor, dashArray });
            const markers = this.polygonCoords.map(pt =>
                BM.circleMarker([pt.lat, pt.lng], {
                    radius: 6,
                    color: this.strokeColor,
                    fillColor: this.fillColor,
                    fillOpacity: 1
                })
            );
            this.graphicsLayer = BM.layerGroup([polyline, ...markers]).addTo(this.map);
        } else if (this.drawMode === 'polygon' && count >= 3) {
            const latlngs = this.polygonCoords.map(m => [m.lat, m.lng]);
            const polygon = BM.polygon(latlngs, { color: this.strokeColor, fillColor: this.fillColor, fillOpacity: 0.5, dashArray });
            const markers = this.polygonCoords.map(pt =>
                BM.circleMarker([pt.lat, pt.lng], {
                    radius: 6,
                    color: this.strokeColor,
                    fillColor: this.fillColor,
                    fillOpacity: 1
                })
            );
            this.graphicsLayer = BM.layerGroup([polygon, ...markers]).addTo(this.map);
        }
        // 新增：渲染所有历史点
        if (this._pointMarkers) {
            this._pointMarkers.forEach(m => { if (m && this.map.hasLayer(m)) this.map.removeLayer(m); });
        }
        this._pointMarkers = [];
        if (this._pointHistory && this._pointHistory.length > 0) {
            this._pointHistory.forEach(pt => {
                const marker = BM.marker([pt.lat, pt.lng]).addTo(this.map);
                // 右键精确删除点
                marker.on('contextmenu', (e) => {
                    const { lat, lng } = e.target.getLatLng();
                    const idx = this._pointHistory.findIndex(
                        p => Math.abs(p.lat - lat) < 1e-8 && Math.abs(p.lng - lng) < 1e-8
                    );
                    if (idx !== -1) {
                        this._pointHistory.splice(idx, 1);
                        this.drawGraphics();
                        if (this.onClickCallback) this.onClickCallback(this.getCoords());
                    }
                    if (e.originalEvent && e.originalEvent.preventDefault) e.originalEvent.preventDefault();
                    return false;
                });
                this._pointMarkers.push(marker);
            });
        }
        // 渲染所有历史线
        if (this._polylineHistory) {
            this._polylineHistory.forEach(polyline => {
                if (!polyline || !this.map.hasLayer(polyline)) return;
                // 右键精确删除线
                polyline.on('contextmenu', (e) => {
                    const latlngs = polyline.getLatLngs();
                    const idx = this._polylineHistory.findIndex(line => {
                        if (!line) return false;
                        const arr = line.getLatLngs ? line.getLatLngs() : [];
                        if (arr.length !== latlngs.length) return false;
                        return arr.every((pt, i) =>
                            Math.abs(pt.lat - latlngs[i].lat) < 1e-8 && Math.abs(pt.lng - latlngs[i].lng) < 1e-8
                        );
                    });
                    if (idx !== -1) {
                        this.map.removeLayer(this._polylineHistory[idx]);
                        this._polylineHistory.splice(idx, 1);
                        this.drawGraphics();
                    }
                    if (e.originalEvent && e.originalEvent.preventDefault) e.originalEvent.preventDefault();
                    return false;
                });
            });
        }
        // 渲染所有历史多边形
        if (this._polygonHistory) {
            this._polygonHistory.forEach(polygon => {
                if (!polygon || !this.map.hasLayer(polygon)) return;
                // 右键精确删除多边形
                polygon.on('contextmenu', (e) => {
                    const latlngs = polygon.getLatLngs();
                    const idx = this._polygonHistory.findIndex(poly => {
                        if (!poly) return false;
                        const arr = poly.getLatLngs ? poly.getLatLngs() : [];
                        if (arr.length !== latlngs.length) return false;
                        return arr.every((pt, i) =>
                            Math.abs(pt.lat - latlngs[i].lat) < 1e-8 && Math.abs(pt.lng - latlngs[i].lng) < 1e-8
                        );
                    });
                    if (idx !== -1) {
                        this.map.removeLayer(this._polygonHistory[idx]);
                        this._polygonHistory.splice(idx, 1);
                        this.drawGraphics();
                    }
                    if (e.originalEvent && e.originalEvent.preventDefault) e.originalEvent.preventDefault();
                    return false;
                });
            });
        }
        // 渲染所有历史圆
        if (this._circleList) {
            this._circleList.forEach(circle => {
                if (!circle || !this.map.hasLayer(circle)) return;
                // 右键精确删除圆
                circle.on('contextmenu', (e) => {
                    const latlng = circle.getLatLng();
                    const radius = circle.getRadius();
                    const idx = this._circleList.findIndex(c => {
                        if (!c) return false;
                        const cl = c.getLatLng();
                        return Math.abs(cl.lat - latlng.lat) < 1e-8 && Math.abs(cl.lng - latlng.lng) < 1e-8 && Math.abs(c.getRadius() - radius) < 1e-4;
                    });
                    if (idx !== -1) {
                        this.map.removeLayer(this._circleList[idx]);
                        this._circleList.splice(idx, 1);
                        this.drawGraphics();
                    }
                    if (e.originalEvent && e.originalEvent.preventDefault) e.originalEvent.preventDefault();
                    return false;
                });
            });
        }
        // 渲染所有历史围栏
        if (this._fenceHistory) {
            this._fenceHistory.forEach(fence => {
                if (!fence || !this.map.hasLayer(fence)) return;
                // 右键精确删除围栏
                fence.on('contextmenu', (e) => {
                    const latlngs = fence.getLatLngs();
                    const idx = this._fenceHistory.findIndex(f => {
                        if (!f) return false;
                        const arr = f.getLatLngs ? f.getLatLngs() : [];
                        if (arr.length !== latlngs.length) return false;
                        return arr.every((pt, i) =>
                            Math.abs(pt.lat - latlngs[i].lat) < 1e-8 && Math.abs(pt.lng - latlngs[i].lng) < 1e-8
                        );
                    });
                    if (idx !== -1) {
                        this.map.removeLayer(this._fenceHistory[idx]);
                        this._fenceHistory.splice(idx, 1);
                        this.drawGraphics();
                    }
                    if (e.originalEvent && e.originalEvent.preventDefault) e.originalEvent.preventDefault();
                    return false;
                });
            });
        }
        // 渲染所有测距历史
        if (this._distanceHistory) {
            this._distanceHistory.forEach(item => {
                if (item.line && this.map.hasLayer(item.line)) {
                    item.line.on('contextmenu', (e) => {
                        this.map.removeLayer(item.line);
                        if (item.tip) this.map.removeLayer(item.tip);
                        const idx = this._distanceHistory.indexOf(item);
                        if (idx !== -1) this._distanceHistory.splice(idx, 1);
                        if (e.originalEvent && e.originalEvent.preventDefault) e.originalEvent.preventDefault();
                        this.drawGraphics();
                        return false;
                    });
                }
            });
        }
        // 渲染所有面积历史
        if (this._areaHistory) {
            this._areaHistory.forEach(item => {
                if (item.polygon && this.map.hasLayer(item.polygon)) {
                    item.polygon.on('contextmenu', (e) => {
                        this.map.removeLayer(item.polygon);
                        if (item.tip) this.map.removeLayer(item.tip);
                        const idx = this._areaHistory.indexOf(item);
                        if (idx !== -1) this._areaHistory.splice(idx, 1);
                        if (e.originalEvent && e.originalEvent.preventDefault) e.originalEvent.preventDefault();
                        this.drawGraphics();
                        return false;
                    });
                }
            });
        }
    }

    getCoords() {
        return this.polygonCoords;
    }

    reset() {
        this.polygonCoords = [];
        this.drawGraphics();
    }

    /**
     * 坐标数组转字符串
     * @returns {string}
     */
    coordsToString() {
        return this.polygonCoords.map(item => `${item.lat},${item.lng}`).join(';');
    }

    /**
     * 字符串转坐标数组并重绘
     * @param {string} str
     */
    stringToCoords(str) {
        if (!str) return;
        const coords = str.split(';').map(pair => {
            const [lat, lng] = pair.split(',').map(Number);
            return { lat, lng };
        });
        this.setCoords(coords);
    }

    /**
     * 设置坐标并重绘
     * @param {Array} coords
     */
    setCoords(coords) {
        this.polygonCoords = coords;
        this.drawGraphics();
    }

    /**
     * 在地图上添加一个 marker
     * @param {Array} latlng [纬度, 经度]
     * @param {Object} options marker 配置项，可包含iconUrl、iconSize等
     * @returns {Object} marker 实例
     */
    addMarker(latlng, options = {}) {
        if (!this.map) return null;
        // 默认定位图标
        if (!options.iconUrl) {
            // options.iconUrl = require('@/assets/images/dingwei.png');
        }
        if (options.iconUrl) {
            options.icon = BM.icon({
                iconUrl: options.iconUrl,
                iconSize: options.iconSize || [40, 40],
                iconAnchor: options.iconAnchor || [20, 40],
                popupAnchor: options.popupAnchor || [0, -40]
            });
        }
        const marker = BM.marker(latlng, options).addTo(this.map);
        return marker;
    }

    /**
     * 多边形面积计算（球面近似，单位平方米）
     * @param {Array} coords - [{lat, lng}, ...]
     * @returns {number} 面积（平方米）
     */
    _calcPolygonArea(coords) {
        if (!coords || coords.length < 3) return 0;
        const R = 6378137;
        let area = 0;
        for (let i = 0; i < coords.length; i++) {
            const p1 = coords[i];
            const p2 = coords[(i + 1) % coords.length];
            area += (p2.lng - p1.lng) * (2 + Math.sin(p1.lat * Math.PI / 180) + Math.sin(p2.lat * Math.PI / 180));
        }
        area = area * R * R / 2.0;
        return Math.abs(area);
    }

    /**
     * 计算两点的方位角（角度，正北为0，顺时针）
     */
    _calcAzimuth(lat1, lng1, lat2, lng2) {
        const toRad = deg => deg * Math.PI / 180;
        const dLon = toRad(lng2 - lng1);
        const y = Math.sin(dLon) * Math.cos(toRad(lat2));
        const x = Math.cos(toRad(lat1)) * Math.sin(toRad(lat2)) -
                  Math.sin(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.cos(dLon);
        let brng = Math.atan2(y, x) * 180 / Math.PI;
        brng = (brng + 360) % 360;
        return brng;
    }

    /**
     * 回到初始化中心点
     */
    centerToDefaultCenter() {
        if (this.map && this.options.center) {
            this.map.setView(this.options.center, this.options.zoom || 15);
        }
    }

    // 新增：显示回显多边形（回显层，不受工具栏影响）
    showPolygon(coords, fillColor) {
        // 先清除回显层
        if (this._showPolygonLayer) {
            this.map.removeLayer(this._showPolygonLayer);
            this._showPolygonLayer = null;
        }
        // 只在有足够点数时显示
        if (coords && coords.length > 2) {
            // 支持二维数组（如[[{lat,lng},...]]）
            let pts = coords;
            if (Array.isArray(pts) && Array.isArray(pts[0])) {
                pts = pts[0];
            }
            this._showPolygonLayer = BM.polygon(pts, { fillColor: fillColor || '#00ff0033', color: fillColor || '#00ff0033', fillOpacity: 0.4 }).addTo(this.map);
        }
    }
}

export default BigeMapUtils;